package com.bookmanager.www.controller.admin;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookmanager.www.common.Constants.PreferentialConstant;
import com.bookmanager.www.common.DTO.AdvancedSearchDTO;
import com.bookmanager.www.common.DTO.AdvancedSearchOrdersDTO;
import com.bookmanager.www.common.DTO.WeekRateDTO;
import com.bookmanager.www.common.PO.CountAndPricePO;
import com.bookmanager.www.common.utils.CommonsUtils;
import com.bookmanager.www.common.utils.Result;
import com.bookmanager.www.common.vo.AuthorVO;
import com.bookmanager.www.entity.*;
import com.bookmanager.www.entity.author.Author;
import com.bookmanager.www.entity.author.AuthorQr;
import com.bookmanager.www.entity.author.AuthorSkill;
import com.bookmanager.www.mapper.*;
import com.bookmanager.www.service.SearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2021/11/14/18:09
 * @Description:
 */
@RestController
@RequestMapping("/fl-admin")
@Slf4j
@RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
@Api(tags = "管理员管理")
public class AdminController {
    @Resource
    FlBookorderMapper flBookorderMapper;

    @Resource
    FlBookMapper flBookMapper;

    @Resource
    FlUserMapper flUserMapper;

    @Resource
    FlAddressMapper flAddressMapper;

    @Resource
    FlAuthorMapper flAuthorMapper;

    @Resource
    SearchService searchService;

   @PostMapping("/getBookHitsTop")
   @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
   @ApiOperation(value = "获取点击量前十的书籍")
   Result getBookHitsTop(@RequestParam(value = "page",defaultValue = "1") Integer page,
                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize) {
       Page<FlBookHits> p =  new Page<FlBookHits>(page,pageSize);
       List<FlBookHits> mapList = flBookMapper.getBookHitsTop(p);
       IPage<FlBookHits> page1 = p.setRecords(mapList);
       return Result.succ("查询成功",page1);
   }


    @GetMapping("/getRolesList")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation(value = "获取角色列表")
    Result getRolesList() {

        List<EndRole> endRoleList = flUserMapper.getEndRolesList();

        return Result.succ("查询成功",endRoleList);
    }




    @GetMapping("/getAuthorsDetail")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "获取作者详情")
    Result getAuthorsDetail() {
        List<AuthorVO> authorVOS=new LinkedList<>();
        List<Author> authorList = flAuthorMapper.selectAllAuthor();
        for(Author author:authorList){
            AuthorVO authorVO=new AuthorVO();
            authorVO.setAuthor(author);
            List<AuthorQr> authorQrs = flAuthorMapper.selectAuthorQrByAuthorId(author.getAuthorId());
            authorVO.setAuthorQrList(authorQrs);
            List<AuthorSkill> authorSkills =flAuthorMapper.selectAuthorSkillByAuthorId(author.getAuthorId());
            authorVO.setAuthorSkillList(authorSkills);
            authorVOS.add(authorVO);
        }

        return Result.succ("查询成功",authorVOS);
    }

    @PostMapping("advancedSearchOrders")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "高级搜索订单")
    Result advancedSearchOrders(@RequestBody AdvancedSearchOrdersDTO a) {
        FlBookOrder flBookOrder =new FlBookOrder();
        Page<FlBookOrder> p =  new Page<FlBookOrder>(a.getPage(),a.getPageSize());
        List<FlBookOrder> mapList = flBookorderMapper.advancedSearchOrders(p,a);
        IPage<FlBookOrder> page = p.setRecords(mapList);

        return Result.succ("查询成功",page);
    }


    @PostMapping("advancedSearch")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "高级搜索")
    Result advancedSearch(@RequestBody AdvancedSearchDTO advancedSearchDTO) throws IOException {
//        List<Map<String, Object>> mapList =searchService.advancedSearch(advancedSearchDTO);
        FlBook flBook =new FlBook();
        Page<FlBook> p =  new Page<FlBook>(advancedSearchDTO.getPage(),advancedSearchDTO.getPageSize());
        List<FlBook> mapList = flBookMapper.advancedSearch(p,advancedSearchDTO);
        IPage<FlBook> page = p.setRecords(mapList);


        return Result.succ("查询成功",page);

    }

    @GetMapping("getISBNDetail")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "获取ISBN详情")
    Result getISBNDetail(@RequestParam("ISBN")String isbn,@RequestParam("key")String key) throws IOException {
//        String url = "https://api.ibook.tech/v1/book/isbn?isbn=";
//        url=url+isbn+"&uKey="+key;
        String url = "https://api.zuk.pw/situ/book/isbn/";
        url+=isbn;
        url+= PreferentialConstant.apiKey;
        log.warn("url:{}",url);
        String result = sendGet(url);
        log.warn(result);
        com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
//        JSONObject jsonObject = JSONUtil.parseObj(result);
        return Result.succ("查询成功",obj);
    }

//    @PostMapping("changeInventory")
//    @ApiOperation(value="修改库存")
//    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
//    Result changeInventory(@RequestParam("ISBN")String isbn,@RequestParam("newInventory")Integer newInventory)
//    {
//        if(flBookMapper.selectBookByBookId(isbn)==null)
//        {
//            return Result.fail("没有该书籍","");
//        }
//        int updatedInventory = flBookMapper.changeStockByBookId(isbn,newInventory);
//        if(updatedInventory!=0)
//        {
//            return Result.succ("修改库存成功！",newInventory);
//        }
//
//       return Result.fail("更新数据库库存失败！！","");
//    }

//    @GetMapping("/getOrderCountAndPrice")
//    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
//    @ApiOperation(value = "获取本月订单总金额和总数（同比增长）")
    Result getOrderCountAndPrice() throws ParseException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime thisMonth = LocalDateTime.now();
//        LocalDateTime lastMonth = thisMonth.minusMonths(1L);
//        String temp = lastMonth.toString();

        int monthValue = thisMonth.getMonthValue();
        int yearValue = thisMonth.getYear();
        //2021-11-07 15:53:12
        String start = yearValue+"-"+monthValue+"-01"+" 00:00:00";

        String lastMonthStart  = yearValue+"-"+(monthValue-1)+"-01"+" 00:00:00";

        String lastMonthEnd = yearValue+"-"+(monthValue-1)+"-"
                +CommonsUtils.lastDayOfMonth(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastMonthStart)) +" 23:59:59";


        LocalDateTime startTime = LocalDateTime.parse(start,df);
        CountAndPricePO countAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(start,thisMonth.toString());
        CountAndPricePO lastMonthCountAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(lastMonthStart,lastMonthEnd);

        int allCount = countAndPrice.getAllCount();
        int lastMonthCount =lastMonthCountAndPrice.getAllCount();
        BigDecimal allPrice = countAndPrice.getAllPrice();
        BigDecimal lastMonthPrice = lastMonthCountAndPrice.getAllPrice();
        if(lastMonthPrice==null)
        {
            lastMonthPrice=new BigDecimal("1");
        }
        if(lastMonthCount==0)
        {
            lastMonthCount=1;
        }
        if(allPrice==null)
        {
            allPrice=new BigDecimal("1");
        }

        log.info("本月订单总数为："+allCount+"---本月订单总金额为："+allPrice);
        log.info("上月订单总数为："+lastMonthCount+"---上月订单总金额为："+lastMonthPrice);
        double orderCountGrowthRate = (allCount-lastMonthCount)/(double)lastMonthCount;
        BigDecimal orderPriceGrowthRate = (allPrice.subtract(lastMonthPrice)).divide(lastMonthPrice,4,RoundingMode.HALF_UP);
        LinkedHashMap map=new LinkedHashMap();
        Map mapOfMonth = MapUtil.builder().put("allCount",allCount).put("allPrice",allPrice).put("orderCountGrowthRate",orderCountGrowthRate*100+"%")
                .put("orderPriceGrowthRate",orderPriceGrowthRate.multiply(new BigDecimal(100))+"%").build();
        map.put("monthOrderDetail",mapOfMonth);


        return Result.succ("查询成功",mapOfMonth);
    }

    @PostMapping("/getWeekOrderCountAndPrice")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "获取本周/月订单总金额和总数（同比增长）")
    Result getWeekOrderCountAndPrice(@RequestBody WeekRateDTO weekRateDTO) throws ParseException {
        CountAndPricePO countAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(
                weekRateDTO.getThisWeekStart(),weekRateDTO.getThisWeekEnd());
        CountAndPricePO lastWeekCountAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(
                weekRateDTO.getLastWeekStart(),weekRateDTO.getLastWeekEnd());

        int allCount = countAndPrice.getAllCount();
        int lastMonthCount =lastWeekCountAndPrice.getAllCount();
        BigDecimal allPrice = countAndPrice.getAllPrice();
        BigDecimal lastMonthPrice =lastWeekCountAndPrice.getAllPrice();
        if(lastMonthPrice==null)
        {
            lastMonthPrice=new BigDecimal("1");
        }
        if(allPrice==null)
        {
            allPrice=new BigDecimal("1");
        }
        if(lastMonthCount==0)
        {
            lastMonthCount=1;
        }

        log.info("本周订单总数为："+allCount+"---本周订单总金额为："+allPrice);
        log.info("上周订单总数为："+lastMonthCount+"---上周订单总金额为："+lastMonthPrice);

        double orderCountGrowthRate = (allCount-lastMonthCount)/(double)lastMonthCount;
        BigDecimal orderPriceGrowthRate = (allPrice.subtract(lastMonthPrice)).divide(lastMonthPrice,2,RoundingMode.HALF_UP);
        LinkedHashMap map=new LinkedHashMap();
        Map mapOfMonth = MapUtil.builder().put("allCount",allCount).put("allPrice",allPrice).put("orderCountGrowthRate",orderCountGrowthRate*100+"%")
                .put("orderPriceGrowthRate",orderPriceGrowthRate.multiply(new BigDecimal(100))+"%").build();
        map.put("weekOrderDetail",mapOfMonth);
//==========================================================================================================================

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime thisMonth = LocalDateTime.now();
//        LocalDateTime lastMonth = thisMonth.minusMonths(1L);
//        String temp = lastMonth.toString();

        int monthValue = thisMonth.getMonthValue();
        int yearValue = thisMonth.getYear();
        //2021-11-07 15:53:12
        String start = yearValue+"-"+monthValue+"-01"+" 00:00:00";

        String lastMonthStart  = yearValue+"-"+(monthValue-1)+"-01"+" 00:00:00";

        String lastMonthEnd = yearValue+"-"+(monthValue-1)+"-"
                +CommonsUtils.lastDayOfMonth(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(lastMonthStart)) +" 23:59:59";


        LocalDateTime startTime = LocalDateTime.parse(start,df);
        CountAndPricePO countAndPrice2 = flBookorderMapper.getAllCountAndAllPriceByTime(start,thisMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        CountAndPricePO lastMonthCountAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(lastMonthStart,lastMonthEnd);

        int allCount2 = countAndPrice2.getAllCount();
        int lastMonthCount2 =lastMonthCountAndPrice.getAllCount();
        BigDecimal allPrice2 = countAndPrice2.getAllPrice();
        BigDecimal lastMonthPrice2 = lastMonthCountAndPrice.getAllPrice();
        if(lastMonthPrice2==null)
        {
            lastMonthPrice2=new BigDecimal("1");
        }
        if(lastMonthCount2==0)
        {
            lastMonthCount2=1;
        }
        if(allPrice2==null)
        {
            allPrice2=new BigDecimal("1");
        }


        log.info("本月订单总数为："+allCount2+"---本月订单总金额为："+allPrice2);
        log.info("上月订单总数为："+lastMonthCount2+"---上月订单总金额为："+lastMonthPrice2);

        double orderCountGrowthRate2 = (allCount2-lastMonthCount2)/(double)lastMonthCount2;

        BigDecimal orderPriceGrowthRate2 = (allPrice2.subtract(lastMonthPrice2)).divide(lastMonthPrice2,2,RoundingMode.HALF_UP);

        Map mapOfWeek = MapUtil.builder().put("allCount",allCount2).put("allPrice",allPrice2).put("orderCountGrowthRate",orderCountGrowthRate2*100+"%")
                .put("orderPriceGrowthRate",orderPriceGrowthRate2.multiply(new BigDecimal(100))+"%").build();
        map.put("monthOrderDetail",mapOfWeek);

        return Result.succ("查询成功",map);
    }

    @GetMapping("/getAllOrderCountAndPrice")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "获取总订单量/金额")
    Result getAllOrderCountAndPrice()
    {
        String startTime = "2021-11-01 00:00:00";
        String nowTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        CountAndPricePO countAndPrice = flBookorderMapper.getAllCountAndAllPriceByTime(startTime,nowTime);

        return Result.succ("查询成功",countAndPrice);

    }

    @GetMapping("/showAllBooks")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value ="商品总览")
    Result showAllBooks()
    {
        log.warn("进入到商品总览方法中了");
        int allCount = flBookMapper.selectBookCount();
        int disableCount = flBookMapper.selectDisableBookCount();
        int upCount = allCount-disableCount;

        log.warn(MapUtil.builder().put("allCount",allCount).
                put("disableCount",disableCount).put("upCount",upCount).build()+"");

        return Result.succ("查询成功!!",MapUtil.builder().put("allCount",allCount).
                put("disableCount",disableCount).put("upCount",upCount).build());
    }

    @GetMapping("/showAllUsers")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value ="用户总览")
    Result showAllUsers()
    {
        log.warn("进入到用户总览方法中了");
        //所有普通用户数量（这里普通用户是指不是管理员）
        int roleId =0;
        int allCount = flUserMapper.selectUserCount(roleId);
        LocalDateTime now = LocalDateTime.now();
        String thisDay = now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth()+" 00:00:00";
        log.warn(thisDay);
        //这里小bug 待解决
        String lastDayStart= thisDay;
        String lastDayEnd = thisDay;
        if(now.getDayOfMonth()!=1)
        {
            lastDayStart = now.getYear()+"-"+now.getMonthValue()+"-"+(now.getDayOfMonth()-1)+" 00:00:00";
            lastDayEnd = now.getYear()+"-"+now.getMonthValue()+"-"+(now.getDayOfMonth()-1)+" 23:59:59";
        }
        String thisMonthStart = now.getYear()+"-"+now.getMonthValue()+"-"+"01"+" 00:00:00";
        int thisDayNew = flUserMapper.selectUserByCreateTime(thisDay,now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        int lastDayNew = flUserMapper.selectUserByCreateTime(lastDayStart,lastDayEnd);
        int thisMonthNew = flUserMapper.selectUserByCreateTime(thisMonthStart,now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        log.warn(MapUtil.builder(new LinkedHashMap<>())
                .put("thisDayNew",thisDayNew)
                .put("lastDayNew",lastDayNew)
                .put("thisMonthNew",thisMonthNew)
                .put("allCount",allCount).build()+"");
        return Result.succ("查询成功",MapUtil.builder(new LinkedHashMap<>())
                .put("thisDayNew",thisDayNew)
                .put("lastDayNew",lastDayNew)
                .put("thisMonthNew",thisMonthNew)
                .put("allCount",allCount).build());

    }

    @GetMapping("/getDiffLevelUserCount")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value ="会员等级分布图")
    Result getDiffLevelUserCount()
    {
        int roleId=0;
        LinkedHashMap linkedHashMap=new LinkedHashMap();
        for(int level=0;level<9;level++)
        {
           linkedHashMap.put("level"+level,flUserMapper.selectCountByUserLevelAndRoleId(level,roleId));
        }
        return Result.succ("查询成功",linkedHashMap);
    }

    @GetMapping("/selectOrdersByTime") //这里后期有需要可做分页
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "时间段查询订单总数和订单总金额",notes = "传入两个时间段即可")
    Result setOrderByTime(@RequestParam("startTime")String startTime,@RequestParam("endTime")String endTime)
    {
        Instant instA = Instant.now();
//        String startTime = timestamps[0];
//        String endTime = timestamps[1];
        DateTime startDate = DateUtil.parse(startTime);
        DateTime endDate = DateUtil.parse(endTime);
        log.info(String.valueOf(startDate));
        List<FlBookOrder> bookOrderList = flBookorderMapper.selectOrdersByTime(startDate,endDate);
        int totalDays = (int) CommonsUtils.TimeSubtract(startTime,endTime);
        LinkedList everyDays=new LinkedList();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for(int i=0;i<totalDays;i++)
        {
            LocalDateTime flag = LocalDateTime.parse(startTime,df).plusDays(i);
            ArrayList<FlBookOrder> test = new ArrayList();
            for(int j =0;j<bookOrderList.size();j++)
            {
//                log.info("订单中获取的天数:"+bookOrderList.get(j).getCreateTime().getDayOfMonth()+"");
//                log.info("从传入获取的天数"+flag.getDayOfMonth()+"");
//                log.info("========================================================");
                if(bookOrderList.get(j).getCreateTime().getDayOfMonth()==flag.getDayOfMonth()&&
                        bookOrderList.get(j).getCreateTime().getMonthValue()==flag.getMonthValue()
                )
                {
                    test.add(bookOrderList.get(j));
                }
            }

            Integer orderCount = test.size();

            int year = flag.getYear();
            int month = flag.getMonthValue();
            log.info("monthValue---"+month);
            int day = flag.getDayOfMonth();

            String dayName = year+"-"+month+"-"+day;
            log.info(dayName);

            BigDecimal orderAllPrice = new BigDecimal("0");
            for(int k=0;k<test.size();k++)
            {
//                log.info("订单金额为："+test.get(k).getPayment());
                orderAllPrice = orderAllPrice.add(test.get(k).getPayment());
//                log.info("总金额为："+orderAllPrice);
            }
            Map orderDetails = MapUtil.builder().put("day",dayName).put("orderCount",orderCount)
                    .put("orderAllPrice",orderAllPrice).build();
            everyDays.add(orderDetails);
        }
        Instant instB = Instant.now();
        log.info("整个方法所用时间为："+ Duration.between(instA,instB).toMillis()+"ms");

        return Result.succ("查询成功",everyDays);
    }


    @GetMapping("/selectAllOrder")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "全查图书/余额订单",notes = "type = 1 全查图书 2 全查余额")
    Result selectAllOrder(@RequestParam("page")Integer page, @RequestParam("pageSize")Integer pageSize, @RequestParam("type")
            Integer type) throws IOException {
        String flag = "余额充值";
        FlBookOrder flBookOrder =new FlBookOrder();
        Page<FlBookOrder> p = new Page<>(page,pageSize);
        if(type==1)
        {
            IPage<FlBookOrder> bookOrders = p.setRecords(flBookorderMapper.selectAllBookOrder(p,flBookOrder,flag));
            List<FlBookOrder> flBookOrders =bookOrders.getRecords();
            return getBookOrder(flBookOrders,p);
        }else if(type==2)
        {
            IPage<FlBookOrder> bookOrders = p.setRecords(flBookorderMapper.selectAllAccountOrder(p,flBookOrder,flag));
            return Result.succ("查询所有余额订单成功！！",bookOrders);
        }else {
            return Result.fail("输入参数类型有误！！","");
        }

    }


    /**
     * 订单发货
     */
    @PostMapping("/orderDispatch")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical = Logical.OR)
    @ApiOperation(value = "订单发货(单个订单或者批量)",notes = "订单状态从待发货（已支付到）已发货")
    Result orderDispatch(@RequestParam("batchIds")String[] orderIds)
    {
        for (String orderId : orderIds) {
            FlBookOrder flBookOrder=flBookorderMapper.selectOrderByOrderId(orderId);
            if(flBookOrder!=null)
            {
                int status=flBookOrder.getStatus();
                //订单未支付或者已完成 不支持发货
                if(status==0)
                {
                    return Result.fail("订单未支付！！","");
                }else if(status==2)
                {
                    return Result.fail("订单已发货！！","");
                }
                else if(status==3)
                {
                    return Result.fail("订单已完成交易无需重复发货！！","");
                }
                else {
                    int updateStatus = flBookorderMapper.changeStatusByOrderId(orderId,2);
                    if(updateStatus!=0)
                    {
                        log.warn("订单发货成功！！");
                    }else {
                        return Result.fail("数据库未更新状态！！","");
                    }

                }
            }
        }

        return Result.succ("所有订单发货成功！！","");
    }

    @GetMapping("/getAllNormalUserDetail")
    @ApiOperation(value = "获取所有普通用户信息",notes = "需要管理员和超级管理员身份")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical= Logical.OR)
    public Result getAllNormalUserDetail(@RequestParam("page")Integer page,
                                         @RequestParam("pageSize")Integer pageSize)
    {
        Page<FlUser> p =new Page<>(page,pageSize);
        FlUser flUser = new FlUser();
        IPage<FlUser> userDetailList = p.setRecords(flUserMapper.selectRoleUser(p,flUser,0));

        return Result.succ("获取普通用户信息成功！！",userDetailList);
    }

    @GetMapping("/getUserLoginDetailByUserId")
    @ApiOperation(value = "获取用户的登录信息 默认降序排列")
    @RequiresRoles(value = {"admin","superAdmin","超级管理员","商品管理员","订单管理员"},logical= Logical.OR)
    public Result getUserLoginDetailByUserId(@RequestParam("userId")String userId,
                                             @RequestParam("page")Integer page,
                                             @RequestParam("pageSize")Integer pageSize)
    {
        Page<LoginDetail> p = new Page<>(page,pageSize);
        LoginDetail loginDetail=new LoginDetail();
        IPage<LoginDetail> userLoginDetList = p.setRecords(flUserMapper.selectLoginDetailByUserIdPageExt(p,loginDetail,userId));

        return Result.succ("获取用户登录成功",userLoginDetList);
    }




    public Result getBookOrder(List<FlBookOrder> flBookOrders, Page<FlBookOrder> p ) throws IOException {

        ArrayList allOrder =new ArrayList();
        LinkedHashMap orderDetail = new LinkedHashMap<>();

        for(int i=0;i<flBookOrders.size();i++)
        {
            log.info("进入工具类GetAllBookOrderDetailUtils的订单遍历方法了");
            log.info(String.valueOf(flBookOrders.get(i)));
            Instant instA = Instant.now();
            List<FlBookTemp> bookTempList=flBookorderMapper.selectOrderTempByOrderId(flBookOrders.get(i).getOrderId());

            System.out.println("bookTempList长度为："+bookTempList.size());
            //a1 是一个订单的小的组成部分有很多本书
            ArrayList a1 = new ArrayList();
            //a2 包括a1是一个订单的完全体
            ArrayList a2 = new ArrayList();
            Map l2=new LinkedHashMap();

            for(int j=0;j<bookTempList.size();j++)
            {
                Map l1=new LinkedHashMap();
                Map<String, Object> map = searchService.searchBooks(1, bookTempList.get(j).getBookId(), 1, 1).get(1);
                l1.put("bookImg",map.get("img"));
                l1.put("bookTitle",map.get("title"));
                System.out.println("临时"+l1);
                a1.add(l1);
            }
            l2.put("orderStatus",flBookOrders.get(i).getStatus());
            l2.put("orderId",flBookOrders.get(i).getOrderId());
            l2.put("createTime",flBookOrders.get(i).getCreateTime());
            l2.put("paymentTime",flBookOrders.get(i).getPaymentTime());
            l2.put("payment",flBookOrders.get(i).getPayment());

            if(flAddressMapper.selectAddressByAddressId(
                    flBookOrders.get(i).getAddressId()
            )!=null)
            {
                l2.put("receiveName",flAddressMapper.selectAddressByAddressId(
                        flBookOrders.get(i).getAddressId()
                ).getReceiveName());
            }

            a2.add(a1);
            a2.add(l2);
            allOrder.add(a2);
            Instant instB = Instant.now();
            System.err.println("A--B:"+ Duration.between(instA,instB).toMillis());
        }
        log.info((String) new HashMap<>().put("total",p.getTotal()));
        orderDetail.put("orderDetail",allOrder);
        orderDetail.put("total",p.getTotal());
        return Result.succ("查询订单成功！！",orderDetail);
    }

    /**
     * 向接口发送Get请求
     * @param urlParame
     * @return
     * @throws IOException
     */
    public static String sendGet(String urlParame) throws IOException {
        //创建httpclient实例
        HttpClient httpClient=new HttpClient();
        //设置httpclient连接主机服务器超时时间： 以毫秒为单位 1000ms=1s
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        //创建get请求方法实例对象
        GetMethod getMethod=new GetMethod(urlParame);
        //设置get请求超时时间，value以毫秒为单位
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
        //设置请求头
        getMethod.addRequestHeader("Content-Type", "application/json");
        //执行get
        httpClient.executeMethod(getMethod);
        //获取返回数据
        String result=getMethod.getResponseBodyAsString();
        //释放http连接
        getMethod.releaseConnection();

        return result;
    }
}
